import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_syt/application.dart';
import 'package:flutter_syt/generated/assets.dart';
import 'package:flutter_syt/generated/l10n.dart';
import 'package:flutter_syt/theme/theme_color.dart';
import 'package:flutter_syt/utils/global_date_time_format.dart';
import 'package:flutter_syt/utils/utils_dlog.dart';
import 'package:flutter_syt/widgets/auto_image.dart';
import 'package:intl/intl.dart';

class HomeCountDown extends StatefulWidget {
  int countDownTime;

  HomeCountDown({required this.countDownTime});

  @override
  HomeCountDownState createState() => HomeCountDownState();
}

class HomeCountDownState extends State<HomeCountDown> {
  late Duration diffTime;
  Timer? timer1;

  @override
  Widget build(BuildContext context) {
    // var duration = widget.countDownTime - DateTime.now().millisecondsSinceEpoch;
    // var duration = 0;
    // DLog('HomeCountDownState   $duration');

    if (diffTime.inMinutes <= 0) {
      return Container(
        height: 24,
      );
    }
    List<Widget> timeWidget = [];
    // int ss = 1000;
    // int mi = ss * 60;
    // int hh = mi * 60;
    // int dd = hh * 24;
    // int day = duration ~/ dd;
    // if (diffTime.inDays >= 0) {
    //   if (diffTime.inDays > 0) {
    var dayWidget = diffTime.inDays
        .toString()
        .padLeft(2, '0')
        .split("")
        .map((e) => countBG(e))
        .toList();
    timeWidget.addAll(dayWidget);
    timeWidget.addAll([
      Text(
        S.of(context).day,
        style: const TextStyle(
          color: ThemeColor.colorTextB3,
          fontFamily: 'PingFang SC',
          fontSize: 12,
          fontWeight: FontWeight.w500,
        ),
      ),
      SizedBox(
        width: 4,
      )
    ]);
    //   }
    // }
    // else {
    // if (diffTime.inHours > 0) {
    var hourWidget = (diffTime.inHours % 24)
        .toString()
        .padLeft(2, '0')
        .split("")
        .map((e) => countBG(e))
        .toList();
    timeWidget.addAll(hourWidget);
    timeWidget.addAll([
      Text(
        S.of(context).hour,
        style: const TextStyle(
          color: ThemeColor.colorTextB3,
          fontFamily: 'PingFang SC',
          fontSize: 12,
          fontWeight: FontWeight.w500,
        ),
      ),
      SizedBox(
        width: 4,
      )
    ]);
    // }
    var minrWidget = (diffTime.inMinutes % 60)
        .toString()
        .padLeft(2, '0')
        .split("")
        .map((e) => countBG(e))
        .toList();
    timeWidget.addAll(minrWidget);
    timeWidget.addAll([
      Text(
        S.of(context).minute,
        style: TextStyle(
          color: Color(0xff111111),
          fontFamily: 'PingFang SC',
          fontSize: 13,
          fontWeight: FontWeight.w400,
        ),
      )
    ]);
    var local =
        appContext.storage.getString("storyLocal") ?? Intl.getCurrentLocale();
    // if (local.contains('zh')) {
    return Container(
        // height: 38,
        padding: EdgeInsets.symmetric(horizontal: 16),
        margin: EdgeInsets.only(bottom: 12, top: 12),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            // Container(
            //   width: 113.w,
            //   height: 40.w,
            //   decoration: const BoxDecoration(
            //     image: DecorationImage(
            //         image: AssetImage(
            //           Assets.homeCountBg,
            //         ),
            //         fit: BoxFit.contain,
            //         alignment: Alignment.centerRight),
            //   ),
            //   alignment: Alignment.center,
            //   child:
            AutoImage(
              local.contains('zh')
                  ? Assets.homeCountDay
                  : Assets.homeCountDayEn,
              fit: BoxFit.fitWidth,
              height: 40.w,
            ),
            // ),
            // Text(
            //   S.of(context).note_start(homeDormatDate(widget.countDownTime)),
            //   style: TextStyle(
            //     fontSize: 13.5.sp,
            //     color: Color(0xff111111),
            //     fontWeight: FontWeight.w400,
            //     fontFamily: 'PingFang SC',
            //   ),
            // ),
            // SizedBox(
            //   width: 6,
            // ),
            Row(
              children: timeWidget,
            )
          ],
        ));
  }

  Widget countBG(String text) {
    return Container(
      alignment: Alignment.center,
      margin: const EdgeInsets.only(right: 3),
      width: 22,
      height: 26,
      decoration: BoxDecoration(
          color: ThemeColor.hex('#E2FAF8'),
          border: Border.all(
            width: 1,
            color: ThemeColor.colorPrimaryA2,
          ),
          borderRadius: BorderRadius.circular(6)),
      child: Text(
        text,
        style: const TextStyle(
          fontSize: 13,
          color: ThemeColor.colorPrimaryA1,
          fontWeight: FontWeight.w600,
        ),
      ),
    );
  }

  getNewDiff() {
    var startDate = DateTime.now();
    var endDate =
        DateTime.fromMillisecondsSinceEpoch(widget.countDownTime, isUtc: true);
    diffTime = endDate.difference(startDate);
    // int total = 70 + 60*60 *25;
    // diffTime = Duration(seconds: total);
    // diffTime.inDays == 0 &&
    // DLog('msg123123  ${diffTime.inMinutes}');
    if (timer1 == null && diffTime.inMinutes > 0) {
      timer1 = Timer.periodic(const Duration(seconds: 1), (timer) {
        // int downTime =
        //     widget.countDownTime - DateTime.now().millisecondsSinceEpoch;

        // if ((downTime ~/ 1000) % 60 == 0) {
        // DLog('msg  ${diffTime.inSeconds}');
        var startDate = DateTime.now();
        var endDate = DateTime.fromMillisecondsSinceEpoch(widget.countDownTime,
            isUtc: true);
        diffTime = endDate.difference(startDate);
        // total--;
        // diffTime = Duration(seconds: total);
        if (mounted) {
          setState(() {});
        }
        // }
        if (diffTime.inMinutes <= 0) {
          timer.cancel();
          timer1 = null;
        }
        // getNewDiff();

        // }
      });
    }
  }

  @override
  void initState() {
    super.initState();
    getNewDiff();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  void didUpdateWidget(HomeCountDown oldWidget) {
    super.didUpdateWidget(oldWidget);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }
}
